<template>
  <div>
    <el-tabs
      ref="versionManageTabs"
      v-model="activeName"
      class="demo-tabs"
      :lazy="true"
      @click="versionManageTabsChange"
      @tab-change="tabChange"
    >
      <el-tab-pane
        v-for="(tabItem, tabIndex) in tabData"
        :key="tabIndex"
        :label="tabItem.label"
        :name="tabItem.type"
      >
      </el-tab-pane>
    </el-tabs>
    <HETTable
      ref="versionManageTable"
      :tableFields="versionManageTableFields"
      :tableData="versionManagetTableData"
      :enableSearch="false"
      :operationCol="operationCol"
      :headerOperation="activeName >= 2 ? headerOperationAsync : headerOperation"
      :tableCheckbox="true"
      :handleSelectionChange="handleSelectionChange"
      :total="versionListTotal"
      @getTableData="getGuardUpgradeVersion"
    >
    </HETTable>
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500"
      :center="true"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form
        ref="versionForm"
        :model="form"
        class="px-10"
        label-width="90px"
        :rules="rules"
      >
        <el-form-item label="名称" prop="name">
          <el-input disabled class="input-width" v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input class="input-width" v-model="form.version" autocomplete="off" />
        </el-form-item>
        <el-form-item label="文件" prop="policyName" v-if="dialogTitle == '新建版本'">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :limit="1"
            :auto-upload="false"
            :on-exceed="handleExceed"
            :on-change="onChangeFn"
          >
            <template #trigger>
              <el-button :disabled="uploading" type="primary">选择文件</el-button>
            </template>
            <el-progress
              v-if="progressPercent < 100 && progressPercent > 0"
              :percentage="progressPercent"
              :stroke-width="12"
            />
            <template #tip>
              <div class="el-upload__tip text-red">限制1个文件，新文件将覆盖旧文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="uploading" type="primary" @click="queryVersion">
            确认
          </el-button>
          <el-button :disabled="uploading" @click="dialogVisible = false"
            >取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-if="dialogAsync"
      v-model="dialogAsync"
      title="选择分组"
      :center="true"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="config-body">
        <Group :group="false" @chooseGroup="chooseGroup"></Group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirm()">确定</el-button>
          <el-button @click="dialogAsync = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { genFileId } from "element-plus";
import { Plus, Download } from "@element-plus/icons-vue";
import HETTable from "~/components/common/HETTable.vue";
import {
  req_getGuardUpgradeVersion,
  req_setDefault,
  req_delGuardUpgradeVersion,
  req_setGuardUpgradeVersion,
  req_setVersionSync,
} from "~/utils/axios/versionManage.js";
import { ElMessage ,ElMessageBox} from "element-plus";
import { getToken } from "~/utils/storage/cookie.js";
import axios from "axios";
import { urlCombine } from "~/utils/axios/HETAxios.js";
import { useTreeStore } from "~/utils/pinia/tree.js";
const treeStore = useTreeStore();

const successElMessage = () => {
  ElMessage({
    message: "设置成功",
    type: "success",
  });
};
const props = defineProps({
  tabData: {
    type: Array,
    default: [],
  },
});
// 同步
let dialogAsync = ref(false);
let categoryList = ref([]);
const chooseGroup = (data) => {
  categoryList.value = data;
};
const confirm = () => {
  ElMessageBox.confirm(`${activeName.value == 2?'':'升级过程会导致系统重启，'}是否确认升级？`, "客户端版本升级", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    req_setVersionSync({ categoryList: categoryList.value }).then((res) => {
    res.data.succeed ? ElMessage.success("下发成功") : ElMessage.error("下发失败");
    dialogAsync.value = false;
  });
  })
  
};
/***
 *
 *  table
 *
 * **/
// 表格数据存放
const versionManagetTableData = ref();
// 设为默认
const editDefault = (row) => {
  req_setDefault({ id: row.id }).then((res) => {
    if (res.data.succeed) {
      versionManageTable.value.getTableData();
    }
  });
};

// const versionManageTableFields =    reactive([
//     { name: "name", label: "升级包名称"},
//     { name: "version", label: "版本号"},
//     { name: "createTime", label: "上传时间" },
//     { name: "path", label: "存放路径"},
//     { name: "createUser", label: "用户" },
//     { name: "isDefault", label: "设置为默认", ev: editDefault, type: 'switch'  },
// ])
// table ref
const versionManageTable = ref();
// 表格数据请求函数
const getGuardUpgradeVersion = async (countParams, searchParams) => {
  let versionTableParams = {
    os: activeName.value % 2,
    type: activeName.value < 2 ? 1 : 0,
    start: searchParams.$page * searchParams.$limit,
    size: searchParams.$limit,
  };
  await req_getGuardUpgradeVersion(versionTableParams).then((res) => {
    versionManagetTableData.value = res.data.data.map((item) => {
      return {
        ...item,
        isDefault: Boolean(Number(item.isDefault)),
      };
    });
    versionListTotal.value = res.data.total || res.data.length;
  });
  versionManageTable.value.finish();
};
// 版本管理表格数量
const versionListTotal = ref(0);
// 表格单选 选中项
const versionRowData = ref("");
// 表格修改按钮行数据存放
const editVersionRow = ref("");
const editVersion = (index, row) => {
  dialogVisible.value = true;
  dialogTitle.value = "修改版本信息";
  editVersionRow.value = row;
  form.name = row.name;
  form.version = row.version;
};
const delVersion = (index, row) => {
  req_delGuardUpgradeVersion({ id: row.id }).then((res) => {
    if (res.data.succeed) {
      successElMessage();
      versionManageTable.value.getTableData();
    }
  });
};
const operationCol = [
  { name: "修改", ev: editVersion },
  { name: "删除", ev: delVersion, popconfirm: true },
];
const syncFn = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新建版本";
};
const asyncFn = () => {

  if (activeName.value == 2) {
    treeStore.osType = 'win'
  } else if (activeName.value == 3) {
    treeStore.osType = 'linux'
  }
  dialogAsync.value = true;
};
const headerOperationAsync = [
  { name: "下发", ev: asyncFn, icon: Download },
  { name: "新建", ev: syncFn, icon: Plus },
];
const headerOperation = [{ name: "新建", ev: syncFn, icon: Plus }];
// 表格选择check时
const handleSelectionChange = (val) => {
  // HETTable组件的el-table的ref
  let tableRef = versionManageTable.value.getRef();
  // 这部分代码是让复选框设置为单选
  val.map((row, index) => {
    if (val.length <= 1) {
      return;
    }
    tableRef.toggleRowSelection(row, false);
    if (index === val.length - 1) {
      tableRef.toggleRowSelection(row, true);
      versionRowData.value = row;
    }
  });
  if (versionRowData.value === "") {
    versionRowData.value = val[0];
  }
};
/***
 *
 * tabs
 *
 * **/
// tabs ref
const versionManageTabs = ref();
// 当前选择的tabls页
const activeName = ref(props.tabData[0].type);
const versionManageTabsChange = () => {
  versionManageTable.value.getTableData();
};

const getField = () => {
  if (activeName.value < 2) {
    return reactive([
      { name: "name", label: "安装包名称" },
      { name: "version", label: "版本号" },
      { name: "createTime", label: "上传时间" },
      { name: "path", label: "存放路径" },
      { name: "createUser", label: "用户" },
      { name: "isDefault", label: "设置为默认", ev: editDefault, type: "switch" },
    ]);
  } else {
    return reactive([
      { name: "name", label: "升级包名称" },
      { name: "version", label: "版本号" },
      { name: "createTime", label: "上传时间" },
      { name: "path", label: "存放路径" },
      { name: "createUser", label: "用户" },
      { name: "isDefault", label: "设置为默认", ev: editDefault, type: "switch" },
    ]);
  }
};

// 终端版本管理列表 表格列名与数据源设置
const versionManageTableFields = getField();
/**
 *
 * 新增/编辑
 *
 * ***/
// 上传百分比
const progressPercent = ref(0);
// 弹出页上传ref
const upload = ref();
// 弹出页ref
const dialogTitle = ref("新建版本");
// 弹出v-model 控制展示隐藏
const dialogVisible = ref(false);
// 弹出页 form表单ref
const versionForm = ref();
// form表单model
const form = reactive({
  name: "",
  version: "",
  file: "",
});
const rules = reactive({
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  version: [{ required: true, message: "版本号不能为空", trigger: "blur" }],
});
const uploading = ref(false);
// 弹出页提交函数
const queryVersion = () => {
  // debugger
  if (!versionForm) return;
  versionForm.value.validate(async (valid, fields) => {
    if (valid) {
      if (dialogTitle.value == "新建版本") {
        // 创建 FormData 对象
        let getData = {
          os: activeName.value % 2,
          type: activeName.value < 2 ? 1 : 0,
          name: encodeURIComponent(form.name),
          version: encodeURIComponent(form.version),
        };

        let formData = new FormData();
        formData.append("file", form.file);
        uploading.value = true;
        await axios({
          method: "post",
          headers: {
            "Content-Type": "multipart/form-data",
            accesstoken: getToken(),
          },
          url:
            "/api/v2.0/versionManager/version/guardUpgradeVersion?" + urlCombine(getData),
          data: formData,
          onUploadProgress: (progressEvent) => {
            progressPercent.value = Number(
              ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
            );
          },
        })
          .then((res) => {
            if (res.status == 200 && res.data) {
              ElMessage.success("上传成功");
              versionManageTable.value.getTableData();
            } else {
              ElMessage.error("上传失败");
            }
            uploading.value = false;
          })
          .catch((err) => {
            ElMessage.error("上传失败");
            uploading.value = false;
          });
      } else {
        let editVersionParams = {
          id: editVersionRow.value.id,
          name: form.name,
          version: form.version,
        };
        await req_setGuardUpgradeVersion(editVersionParams).then((res) => {
          if (res.data.succeed) {
            successElMessage();
            versionManageTable.value.getTableData();
          }
        });
      }
      dialogVisible.value = false;
      form.name = "";
      form.version = "";
      form.file = "";
    }
  });
};
const onChangeFn = (files) => {
  form.file = files.raw;
  form.name = files.name;
  const regex = "v?(\\d{1,3}\\.){4,5}\\d{1,3}";
  form.version = files.name.match(regex) ? files.name.match(regex)[0] : "";
};
const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};
</script>

<style lang="scss" scoped>
:deep(.el-upload-list) {
  display: none;
}

:deep(.el-progress) {
  width: 300px;
  margin-top: 5px;
}
</style>
